package com.ruoyi.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ProjectPurchase;
import com.ruoyi.system.domain.ProjectPurchaseMaterial;
import com.ruoyi.system.domain.vo.ProjectPurchaseMaterialNumVO;
import com.ruoyi.system.service.IProjectPurchaseMaterialService;
import com.ruoyi.system.service.IProjectPurchaseMaterialService;
import com.ruoyi.system.service.IProjectPurchaseService;
import com.ruoyi.web.controller.project.excel.ZlSheet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpResponse;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 项目采购Controller
 * 
 * @author ruoyi
 * @date 2025-03-11
 */
@RestController
@RequestMapping("/project/purchase/material")
@RequiredArgsConstructor
@Api(tags = "项目采购")
public class ProjectPurchaseMaterialController extends BaseController{

    private final IProjectPurchaseMaterialService projectPurchaseMaterialService;

    private final IProjectPurchaseService projectPurchaseService;


    @GetMapping("/list")
    @ApiOperation("查询项目采购列表")
    public TableDataInfo list(@RequestParam("projectPurchaseId")Integer projectPurchaseId)
    {
        startPage();
        QueryWrapper<ProjectPurchaseMaterial> wrapper = new QueryWrapper<>();
        wrapper.eq("project_purchase_id",projectPurchaseId);
        List<ProjectPurchaseMaterial> list = projectPurchaseMaterialService.list(wrapper);
        return getDataTable(list);
    }



//    @GetMapping(value = "/{id}")
//    @ApiOperation("获取项目采购详细信息")
//    public AjaxResult getInfo(@PathVariable("id") Integer id)
//    {
//        return success(projectPurchaseMaterialService.getById(id));
//    }
//
//
//    @Log(title = "项目采购", businessType = BusinessType.INSERT)
//    @ApiOperation("新增项目采购")
//    @PostMapping("/add")
//    public AjaxResult add(@RequestBody ProjectPurchaseMaterial projectPurchaseMaterial)
//    {
//        boolean save = projectPurchaseMaterialService.save(projectPurchaseMaterial);
//        return toAjax(save);
//    }
//
//
//    @Log(title = "项目采购", businessType = BusinessType.UPDATE)
//    @ApiOperation("修改项目采购")
//    @PostMapping("/edit")
//    public AjaxResult edit(@RequestBody ProjectPurchaseMaterial projectPurchaseMaterial)
//    {
//        boolean result = projectPurchaseMaterialService.updateById(projectPurchaseMaterial);
//        return toAjax(result);
//    }
//
//
//    @Log(title = "项目采购", businessType = BusinessType.DELETE)
//    @ApiOperation("删除项目采购")
//	@PostMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Integer[] ids)
//    {
//        return toAjax(projectPurchaseMaterialService.removeBatchByIds(Arrays.asList(ids)));
//    }

    private void excel(String month,Integer projectId, HttpServletResponse response){
        List<ProjectPurchaseMaterial> listByMonth = projectPurchaseMaterialService.getListByMonth(month,projectId);
        ProjectPurchaseMaterialNumVO totalByMonth = projectPurchaseMaterialService.getTotalByMonth(month,projectId);
        if (listByMonth == null){
            listByMonth = new ArrayList<>();
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        ZlSheet sheet = new ZlSheet(wb);
        sheet.nextRow(50)
                .createCell(sheet.newMergeCell(7,"材料供货月度对账单",true,(short)18).setBackground(IndexedColors.BLUE))
                .nextRow()
                .createNextCell("")
                .createNextCell("")
                .createNextCell("")
                .createNextCell("")
                .createNextCell("")
                .createNextCell("")
                .createNextCell("第202503期")
                .createCell(7,"上海至和教育",false,(short)15)
                .nextRow()
                .nextRow(34)
                .createCell(sheet.newMergeCell(7,"材 料 对 账 情 况",true,(short)15).setBackground(IndexedColors.BLUE))
                .nextRow(25)
                .createNextCell("日期")
                .createNextCell("材料名称及规格")
                .createNextCell("数量")
                .createNextCell("单位")
                .createNextCell("单价")
                .createNextCell("金额")
                .createNextCell("备注");
        listByMonth.forEach(m->{
            sheet.nextRow(25).createNextCell(new SimpleDateFormat("yyyy-MM-dd").format(m.getCreatedTime()))
                    .createNextCell(m.getName()+m.getSpecification())
                    .createNextCell(m.getNumber())
                    .createNextCell(m.getUnit())
                    .createNextCell(m.getUnitPrice())
                    .createNextCell(m.getPrice())
                    .createNextCell("");
        });
        sheet.nextRow(25)
                .createCell(2,"本月合计数量",true,25,(short)13)
                .createNextCell(totalByMonth == null ? 0 : totalByMonth.getMonthNum(),true,25,(short)13)
                .createCell(5,"本月合计金额",true,25,(short)13)
                .createCell(7,totalByMonth == null ? 0 : totalByMonth.getMonthPrice(),true,25,(short)13)
                .nextRow(25)
                .createCell(2,"至上期止累计供货数量",true,25,(short)13)
                .createNextCell(totalByMonth == null ? 0 : totalByMonth.getLastTotalNum(),true,25,(short)13)
                .createCell(5,"至上期止累计供货金额",true,25,(short)13)
                .createCell(7,totalByMonth == null ? 0 : totalByMonth.getLastTotalPrice(),true,25,(short)13)
                .nextRow(25)
                .createCell(2,"累计供货数量",true,25,(short)13)
                .createNextCell(totalByMonth == null ? 0 : totalByMonth.getTotalNum(),true,25,(short)13)
                .createCell(5,"累计供货金额",true,25,(short)13)
                .createCell(7,totalByMonth == null ? 0 : totalByMonth.getTotalPrice(),true,25,(short)13);
        sheet.nextRow()
                .nextRow(34)
                .createCell(sheet.newMergeCell(7,"开 票 支 付 明 细",true,(short)15).setBackground(IndexedColors.BLUE))
                .nextRow(25)
                .createNextCell("日期",true,25,(short)13)
                .createCell(3,"开票金额",true,25,(short)13)
                .createCell(5,"支付方式",true,25,(short)13)
                .createCell(7,"支付金额",true,25,(short)13);
        sheet.nextRow()
                .createNextCell("")
                .createCell(3,"",false)
                .createCell(5,"",false)
                .createCell(7,"",false)
                .nextRow(25)
                .createNextCell("开票金额",true,25,(short)13)
                .createCell(3,"",true,25,(short)13)
                .createCell(5,"累计支付金额",true,25,(short)13)
                .createCell(7,"",true,25,(short)13)
                .nextRow(25)
                .createNextCell("累计欠款金额",true,25,(short)13)
                .createCell(5,"",true,25,(short)13)
                .createCell(7,"",true,25,(short)13)
                .nextRow(40)
                .createCell(2,"需方签章确认：",true,25,(short)13)
                .createCell(4,"",true,25,(short)13)
                .createNextCell("供方签章确认：",true,25,(short)13)
                .createCell(7,"",true,25,(short)13)
                .nextRow(30)
                .createCell(2,"日  期：",true,25,(short)13)
                .createCell(4,"",true,25,(short)13)
                .createNextCell("日  期：",true,25,(short)13)
                .createCell(7,"",true,25,(short)13);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/export")
    public void export(@RequestParam("month")String month,@RequestParam(value = "projectId",required = false)Integer projectId,HttpServletResponse response){
        excel(month,projectId,response);
    }
}
